<!-- 客户详情-客户联系人页面 -->
<template>
  <div class="client-contact">
    <a-space
      :style="{
        marginBottom: '10px',
      }"
    >
      <a-button
        :style="{
          height: '40px',
        }"
        type="primary"
        @click="showModal"
      >
        <template #icon>
          <icon-plus />
        </template>
        <template #default>新增联系人</template>
      </a-button>
    </a-space>

    <TableTurn
      :isShowPagination="false"
      ref="tableRef"
      :table-data="getContactData"
      :args="args"
    >
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        title="联系人姓名"
        dataIndex="name"
        align="center"
        :width="120"
      >
      </a-table-column>

      <a-table-column
        title="联系电话"
        :width="150"
        dataIndex="phone"
        align="center"
      >
      </a-table-column>
      <a-table-column title="职务" :width="100" dataIndex="job" align="center">
      </a-table-column>
      <a-table-column
        title="部门"
        :width="100"
        dataIndex="department"
        align="center"
      >
      </a-table-column>
      <a-table-column
        title="办公地点"
        :width="300"
        dataIndex="address"
        align="center"
      >
      </a-table-column>
      <a-table-column
        title="决策作用"
        :width="200"
        dataIndex="decision"
        align="center"
      >
      </a-table-column>
      <a-table-column
        :width="150"
        title="是否为首要联系人"
        dataIndex="primaryContact"
        align="center"
        :sortable="{
          sortDirections: ['descend'],
        }"
      >
        <template #cell="{ record }">
          {{ record.primaryContact === 0 ? '否' : '是' }}
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        title="是否为决策关键人"
        dataIndex="primaryDecision"
        align="center"
        :sortable="{
          sortDirections: ['descend'],
        }"
      >
        <template #cell="{ record }">
          {{ record.primaryDecision === 0 ? '否' : '是' }}
        </template>
      </a-table-column>

      <!-- 操作item -->
      <a-table-column align="center" :width="150" fixed="right" title="操作">
        <template #cell="{ record, rowIndex }">
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goEdit(record)"
            />
          </a-tooltip>
          <a-tooltip content="删除">
            <a-popconfirm
              @ok="deleteItem(record.id, rowIndex)"
              content="确定删除吗"
              type="error"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
    <addContact
      v-model:visible="isShowModal"
      @addContactEmit="addContactEmit"
      :detailInfo="currDetailInfo"
    ></addContact>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { useOrderStore } from '@/store';
  import { cloneDeep } from 'lodash';
  import { Message } from '@arco-design/web-vue';
  import { IClientAddContact } from '@/types/order';
  import {
    GetClientDetailTabs,
    PostClientDetailContact,
    DelClientDetailContact,
    PutClientDetailContact,
  } from '@/api/order-management/client-management/client-list';
  import addContact from './components/add-contact/index.vue';

  const route = useRoute();
  const store = useOrderStore();
  let clientId = Number(route.query.id);

  // 表格配置
  const args = reactive({
    stripe: true,
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
  });

  let tableRef = ref(); // 储存table的ref

  let currDetailInfo = ref<IClientAddContact>({
    name: '', // 联系人名称
    phone: '', // 联系电话
    job: '', // 职务
    department: '', // 部门
    address: '', // 办公地点
    decision: '', // 决策作用
    primaryContact: '0', // 是否为首要联系人， 0为否， 1为是
    primaryDecision: '0', // 是否为决策关键人， 0为否， 1为是
    avatar: '', // 头像
    customerId: clientId,
  }); // 储存当前点击表格编辑哪一行的数据

  // 获取客户联系人信息
  const getContactData = async () => {
    try {
      const res = await GetClientDetailTabs({
        id: clientId,
        typeId: 4,
        pageData: {
          page: 0,
          size: -1,
        },
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let isShowModal = ref(false); // 判断是否显示添加联系人弹出框

  // 新增联系人按钮
  const showModal = () => {
    currDetailInfo.value = {
      name: '', // 联系人名称
      phone: '', // 联系电话
      job: '', // 职务
      department: '', // 部门
      address: '', // 办公地点
      decision: '', // 决策作用
      primaryContact: '0', // 是否为首要联系人， 0为否， 1为是
      primaryDecision: '0', // 是否为决策关键人， 0为否， 1为是
      avatar: '', // 头像
      customerId: clientId,
    };
    isShowModal.value = true;
  };

  // 添加联系人弹出框返回的自定义事件
  const addContactEmit = async (form: any, type: string) => {
    try {
      if (type === 'add') await PostClientDetailContact(form);
      else {
        /* 
          深拷贝修改之前tablelist的数据，并赋值成最新的数据
          根据id判断刚刚修改哪一行，并赋值最新的首要联系人或者首要决策人
          然后根据count1和count2的长度来判断，如果0的数量 === list的长度则弹出错误提示
          否则则可以修改成功
        */
        const currList = cloneDeep(tableRef.value.tableList);
        currList.forEach((item: any) => {
          if (item.id === form.id) {
            item.primaryContact = form.primaryContact;
            item.primaryDecision = form.primaryDecision;
          }
        });
        let count1 = 0;
        let count2 = 0;
        for (let i of currList) {
          if (i.primaryContact === '0') count1 += 1;
          if (i.primaryDecision === '0') count2 += 1;
        }
        if (
          count1 === tableRef.value.tableList.length ||
          count2 === tableRef.value.tableList.length
        ) {
          Message.error('至少有一位首要联系人或者首要决策人！');
        } else {
          await PutClientDetailContact(form);
          if (form.primaryContact === '1') store.currContactName = form.name;
        }
      }
      tableRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 编辑按钮
  const goEdit = (form: any) => {
    isShowModal.value = true;
    currDetailInfo.value = form;
  };

  // 删除按钮
  const deleteItem = async (id: number, rowIndex: number) => {
    try {
      await DelClientDetailContact({
        id,
      });
      tableRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  .client-contact {
    padding: 0px 20px;
  }

  :deep(.arco-space) {
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
  }
</style>
